package com.sikaryofficial.common.security.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.common.core.constant.SecurityConstants;
import com.sikaryofficial.common.core.context.SecurityContextHolder;
import com.sikaryofficial.common.core.utils.ServletUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.common.security.auth.AuthUtil;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author ruoyi
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(HeaderInterceptor.class);

    private void processBusiness(HttpServletRequest request) {
        String channel = ServletUtils.getHeader(request, SecurityConstants.CHANNEL_KEY);
        String device = ServletUtils.getHeader(request, SecurityConstants.DEVICE_KEY);
        String brand = ServletUtils.getHeader(request, SecurityConstants.BRAND_KEY);
        // 设置 登录业务渠道 (mobile : 移动端H5 ,pc : 后端管理PC端)
        if (CharSequenceUtil.isNotBlank(channel)) {
            channel = channel.toLowerCase(Locale.ROOT);
        }
        SecurityContextHolder.setChannel(channel);
        // 设置 登录设备 (mobile : 移动设备 ,pc : PC设备)
        if (CharSequenceUtil.isNotBlank(device)) {
            device = device.toLowerCase(Locale.ROOT);
        }
        SecurityContextHolder.setDevice(device);
        // 设置品牌  ( SKE、MEMERS、VFLY、SIKARY )
        if (CharSequenceUtil.isNotBlank(brand)) {
            brand = brand.toUpperCase(Locale.ROOT);
        }
        SecurityContextHolder.setBrand(brand);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
        // 业务头部信息处理
        processBusiness(request);
        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token)) {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser)) {
                AuthUtil.verifyLoginUserExpire(loginUser, SecurityUtils.getChannel(), SecurityUtils.getDeviceId());
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.remove();
    }
}
